package com.kgc.zuulConfig;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;

public class PreFiler extends ZuulFilter {
    /*
    * 过滤器的类型
    * */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    /*
    * 过滤器的顺序
    * */
    @Override
    public int filterOrder() {
        return 0;
    }
    /*
     * 是否拦截过滤
     * */
    @Override
    public boolean shouldFilter() {
        return true;
    }
    /*
     * 确认拦截之后的方法
     * */
    @Override
    public Object run() {
        //获取Request
        RequestContext context=RequestContext.getCurrentContext();
        HttpServletRequest request=context.getRequest();
        //获取token
        String token=request.getHeader("token");
        //获取请求连接
        String requestUrl = request.getRequestURI().toString();
        if (requestUrl.split("/")[3].equals("p")){
            //此接口不需要token认证，直接放行
            return "pass";
        }

        //验证token
        if (token ==null || token.equals("token")){
            //控制是否继续转发请求  true(默认)转发  false不转发
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.setResponseBody("401");
            return "Access denied";
        }
        return "pass";
    }
}
